package com.qyhl.webtv.module_news.news.adv;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.just.library.WebDefaultSettingsManager;
import com.just.library.WebSettings;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.share.ShareUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.weavey.loading.lib.LoadingLayout;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/24.
 * 广告详情
 */

@Route(path = ARouterPathConstant.ADV)
public class AdvertisementActivity extends BaseActivity implements AdvertisementContract.AdvertisementView {
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.share_btn)
    ImageView shareBtn;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.web_layout)
    LinearLayout webLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.finish_btn)
    ImageButton finishBtn;

    private AdvertisementPresenter mPresenter;

    @Autowired(name = "title")
    String mTitle;
    @Autowired(name = "url")
    String mUrl;
    @Autowired(name = "id")
    String newsId;
    @Autowired(name = "hasShare")
    boolean hasShare;
    @Autowired(name = "hasJS")
    boolean hasJS;

    private AgentWeb mAgentWeb;
    private WebView mWebView;

    public static final int FILECHOOSER_RESULTCODE_5 = 12;
    public static final int FILECHOOSER_RESULTCODE = 13;
    public WebChromeClient.FileChooserParams mfileChooserParams;
    public ValueCallback<Uri[]> umUploadMessages;
    public ValueCallback<Uri> mUploadMessage;


    /**
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_adv_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new AdvertisementPresenter(this);
        initView();
        if (StringUtils.isNotEmpty(newsId)) {
            mPresenter.count(newsId);
        }
    }

    @Override
    protected void setListener() {
        setListeners();
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Success);

        if (hasShare) {
            shareBtn.setVisibility(View.VISIBLE);
        } else {
            shareBtn.setVisibility(View.INVISIBLE);
        }

        try {
            if (mUrl.equals(CommonUtils.getInstance().getComplainUrl())) {
                shareBtn.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            Toasty.normal(this, "广告链接出错！").show();
            finish();
        }

        title.setText(StringUtils.isEmpty(mTitle) ? "" : mTitle);//设置标题

        WebViewClient mWebViewClient = new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.cancel();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadMask.setStatus(LoadingLayout.Success);
            }

        };

        WebChromeClient webChromeClient = new WebChromeClient() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                umUploadMessages = filePathCallback;
                mfileChooserParams = fileChooserParams;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String[] acceptTypes = mfileChooserParams.getAcceptTypes();
                if (acceptTypes[0].equals("video/*")) {
                    i.setType("video/*");
                } else if (acceptTypes[0].equals("image/*")) {
                    i.setType("image/*");
                }
                startActivityForResult(Intent.createChooser(i, "选择相册"), FILECHOOSER_RESULTCODE_5);
                return true;
            }

            // For Android > 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                if (acceptType.equals("video/*")) {
                    i.setType("video/*");
                } else if (acceptType.equals("image/*")) {
                    i.setType("image/*");
                }
                startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE);
            }

            /*** 视频播放相关的方法 **/
            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(AdvertisementActivity.this);
                frameLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @SuppressLint("SourceLockedOrientationActivity")
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                showCustomView(view, callback);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//播放时横屏幕，如果需要改变横竖屏，只需该参数就行了
            }

            @SuppressLint("SourceLockedOrientationActivity")
            @Override
            public void onHideCustomView() {
                hideCustomView();
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//不播放时竖屏
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }
        };

        mAgentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(webLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .defaultProgressBarColor() // 使用默认进度条颜色
                .setWebSettings(new CustomSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(webChromeClient)
                .setReceivedTitleCallback(new ChromeClientCallbackManager.ReceivedTitleCallback() {
                    @Override
                    public void onReceivedTitle(WebView view, String title) {

                    }
                })//设置 Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(mUrl);


        if (hasJS) {
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new MyJavaScriptInterface(AdvertisementActivity.this));
        }

        mWebView = mAgentWeb.getWebCreator().get();
    }


    /**
     * 设置监听
     */
    private void setListeners() {
        //返回键监听
        back.setOnClickListener(v -> {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }
        });

        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //分享按钮监听
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(AdvertisementActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        ShareUtils.getInstance().doShare(AdvertisementActivity.this, mUrl, StringUtils.isEmpty(mTitle) ? "广告" : mTitle, "", "", new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {

                            }

                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                Toasty.normal(AdvertisementActivity.this, "分享成功！", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                Toasty.normal(AdvertisementActivity.this, "分享失败！", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {

                            }
                        });
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(AdvertisementActivity.this);
                    }
                });
            }
        });
    }

    class CustomSettings extends WebDefaultSettingsManager {
        protected CustomSettings() {
            super();
        }

        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public WebSettings toSetting(WebView webView) {
            super.toSetting(webView);
            String path = Environment.getExternalStorageDirectory().getPath() + "/baidudata";//百度地图调用需要
            File tmpFile = new File(path);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            getWebSettings().setGeolocationDatabasePath(path);
            getWebSettings().setGeolocationEnabled(true);
            if (hasJS) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWebSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                }
                getWebSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            }
            getWebSettings().setJavaScriptEnabled(true);
            getWebSettings().setDomStorageEnabled(true);
            getWebSettings().setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
            getWebSettings().setAllowFileAccess(false); //允许加载本地文件html  file协议, 这可能会造成不安全 , 建议重写关闭
            getWebSettings().setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            getWebSettings().setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源
            getWebSettings().setUseWideViewPort(true);
            getWebSettings().setUserAgentString("Android");
            getWebSettings().setSupportZoom(true);
            getWebSettings().setBuiltInZoomControls(true);
            return this;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//监听返回键，如果可以后退就后退
            if (customView != null) {
                hideCustomView();
            } else if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, keyEvent);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("广告详情");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("广告详情");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        setResult(1);
        super.onDestroy();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            if (null == data) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            } else {
                Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE_5) {// 5.0适配，主要是因为5.0的返回参数不同。
            // 处理5.0的callback
            if (umUploadMessages != null) {
                if (null != data) { // 5.0的处理方式不同，要注意。
                    ArrayList<String> resultList = data.getStringArrayListExtra("data");
                    umUploadMessages.onReceiveValue(mfileChooserParams.parseResult(resultCode, data));
                    umUploadMessages = null;
                } else {
                    umUploadMessages.onReceiveValue(null);
                }
            }
        }
    }

    private class MyJavaScriptInterface {
        private Context context;

        public MyJavaScriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public String getToken() {
            return SpfManager.getInstance(context).getString("token", "");
        }

        @JavascriptInterface
        public void putToken(String token) {
            SpfManager.getInstance(context).putString("token", token);
        }

        @JavascriptInterface
        public void deleteToken() {
            SpfManager.getInstance(context).remove("token");
        }

    }

    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        AdvertisementActivity.this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(AdvertisementActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        mWebView.setVisibility(View.VISIBLE);
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


}
